<template>
  <!---------- 查询表单form begin ----------->
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">
      <a-form-item label="日志类别" class="smart-query-form-item">
        <a-select ref="select" v-model:value="queryForm.level" style="width: 200px" placeholder="请选择日志类别">
          <a-select-option v-for="item in levelList" :key="item.value" :value="item.value">{{ item.label }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item class="smart-query-form-item">
        <a-button type="primary" @click="queryData">
          <template #icon>
            <SearchOutlined />
          </template>
          查询
        </a-button>
        <a-button @click="resetQuery" class="smart-margin-left10">
          <template #icon>
            <ReloadOutlined />
          </template>
          重置
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true">
    <div class="log-card">
      <div class="log-left" :class="{ 'log-left-flex': fileDirState }">
        <!---------- 表格操作行 begin ----------->
        <a-row class="smart-table-btn-block">
          <div class="smart-table-operate-block"></div>
          <div class="smart-table-setting-block">
            <TableOperator v-model="columns" :tableId="null" :refresh="queryData" />
          </div>
        </a-row>
        <!---------- 表格操作行 end ----------->
        <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="deviceId" bordered :loading="tableLoading" :pagination="false">
        <template #bodyCell="{ record, column }">
          <template v-if="column.dataIndex === 'logName'">
            <div
              style="color: #1677ff"
              @click="onClick(record)"
              @contextmenu.prevent="showContextMenu($event, record)"
            >{{ record.logName }}</div>
          </template>
          <template v-if="column.dataIndex === 'logSize'">
            <div>{{ record.logSize }} bytes</div>
          </template>
        </template>
        </a-table>
        <!-- 右键菜单 -->
        <div v-if="contextMenuVisible && selectedRecord" class="context-menu" :style="contextMenuStyle">
            <div class="context-menu-item" @click="downloadLog(selectedRecord)">
              <DownloadOutlined /> 下载日志
            </div>
        </div>
      </div>
      <div class="log-right" v-if="fileDirState">
        <div class="log-right-title">{{ fileDir }}</div>
        <div class="log-right-body" v-html="fileDirContent"></div>
      </div>
    </div>
  </a-card>
</template>
<script setup>
  import { ref, onMounted, watch, onUnmounted } from 'vue';
  import { message } from 'ant-design-vue';
  import { DownloadOutlined } from '@ant-design/icons-vue';
  import { iotApi } from '/@/api/business/iotLog/index.js';
  import TableOperator from '/@/components/support/table-operator/index.vue';

  const columns = ref([
    {
      title: '日志名称',
      dataIndex: 'logName',
    },
    {
      title: '上次修改时间',
      dataIndex: 'lastModified',
    },
    {
      title: '日志大小',
      dataIndex: 'logSize',
    },
  ]);

  const tableData = ref([]);
  const tableLoading = ref(false);
  const levelList = [
    {
      label: 'ERROR',
      value: 'ERROR',
    },
    {
      label: 'INFO',
      value: 'INFO',
    },
    {
      label: 'WARN',
      value: 'WARN',
    },
    {
      label: 'DEBUG',
      value: 'DEBUG',
    },
  ];
  const queryForm = ref({
    level: levelList[0].value,
  });
  const fileDirContent = ref('');
  const fileDirState = ref(false);
  const fileDir = ref('');

  // 重置查询条件
  function resetQuery() {
    queryData();
  }
  // 查询数据
  function queryData() {
    iotApi.getLogByLevel(queryForm.value.level).then(({ data }) => {
      tableData.value = data;
    });
  }

  function onClick(row) {
    fileDir.value = row.fileDir;
    iotApi.getLogContent({ fileDir: row.fileDir }).then(({ data }) => {
      fileDirState.value = true;
      fileDirContent.value = data;
    });
  }
  // 修改变量名，更明确表示其用途
  const selectedRecord = ref(null);
const contextMenuVisible = ref(false);
  const contextMenuStyle = ref({
    left: '0px',
    top: '0px'
  });
  const currentRecord = ref(null);

  // 显示右键菜单
  function showContextMenu(event, record) {
    event.preventDefault();
    // 保存选中的记录
    selectedRecord.value = record;
    contextMenuVisible.value = true;
    contextMenuStyle.value = {
      left: event.clientX + 'px',
      top: event.clientY + 'px'
    };
  }

  // 下载日志
  async function downloadLog(record) {
    if (!record?.fileDir) {
      message.error('文件路径不存在');
      return;
    }

    try {
      const { data } = await iotApi.getLogContent({ fileDir: record.fileDir });

      const blob = new Blob([data], { type: 'text/plain;charset=utf-8' });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = record.logName;

      document.body.appendChild(link);
      link.click();

      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);

      message.success('下载成功');
    } catch (error) {
      console.error('下载失败:', error);
      message.error('下载失败');
    } finally {
      hideContextMenu();
    }
  }

  // 隐藏右键菜单
  function hideContextMenu() {
    contextMenuVisible.value = false;
    selectedRecord.value = null;
  }

  // 点击其他地方时隐藏右键菜单
  function handleClickOutside(event) {
    const contextMenu = document.querySelector('.context-menu');
    if (contextMenuVisible.value && contextMenu && !contextMenu.contains(event.target)) {
      hideContextMenu();
    }
  }

  onMounted(() => {
    document.addEventListener('click', handleClickOutside);
  });

  onUnmounted(() => {
    document.removeEventListener('click', handleClickOutside);
  });

  onMounted(queryData);
</script>

<style scoped>
  .smart-table-operate {
    display: flex;
    justify-content: space-between;
  }
  .device-menu-item:hover {
    color: #1677ff;
  }
  .log-card {
    display: flex;
    height: calc(100vh - 40px - 41px - 10px - 52px - 50px);
    overflow: hidden;
  }
  .log-left {
    width: 100%;
    height: 95%;
    overflow-y: scroll;
    overflow-x: hidden;
    padding-right: 20px;
  }
  .log-left-flex {
    width: 50%;
  }
  .log-right {
    width: 50%;
    height: 95%;
    margin: 20px;
    border-radius: 10px;
    padding: 10px 30px 20px;
    border: 2px solid #ddd;
  }
  .log-right-title {
    height: 30px;
    line-height: 30px;
    font-size: 16px;
    color: #1677ff;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    word-break: break-all;
  }
  .log-right-body {
    height: calc(100% - 30px - 15px);
    overflow: scroll;
    border-top: 1px solid #ccc;
    padding-top: 5px;
  }
  .context-menu {
    position: fixed;
    background: white;
    border: 1px solid #eee;
    border-radius: 4px;
    padding: 4px 0;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    z-index: 1000;
  }

  .context-menu-item {
    padding: 8px 16px;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .context-menu-item:hover {
    background-color: #f5f5f5;
  }
</style>
